package com.icc.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    ImageView img;
    Button btn;
    EditText input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        img = findViewById(R.id.img);
        btn = findViewById(R.id.btn);
        input = findViewById(R.id.input);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str = input.getText().toString();
                            if (TextUtils.isEmpty(str)) {
                                str = "https://tse3-mm.cn.bing.net/th/id/OIP-C.vIRaWM03EDH0Q-ZqpOKqdgHaE5?pid=ImgDet&rs=1";
                            }
                            URL url = new URL(str);
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                            Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
                            //更新UI
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    img.setImageBitmap(bitmap);
                                }
                            });
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });


    }
}